using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using Sunny.UI;
using Sunny.UI.Win32;
using WinApp.Models;
using WinApp.Services;
using static Sunny.UI.UIImageListBox;

namespace WinApp.Pages
{
    public partial class PageAvatars : UIPage
    {
        #region 属性
        private WebView2 _webView2;
        private PageImageMatchActions _pageImageMatchActions = null;
        public PageImageMatchActions ImageMatchPage
        {
            set { _pageImageMatchActions = value; }
        }

        public int X1
        {
            get => int.TryParse(txtLeftX.Text, out int x) ? x : 0;
            set => txtLeftX.Text = value.ToString();
        }

        public int Y1
        {
            get => int.TryParse(txtTopY.Text, out int y) ? y : 0;
            set => txtTopY.Text = value.ToString();
        }

        public int X2
        {
            get => int.TryParse(txtRightX.Text, out int x) ? x : 0;
            set => txtRightX.Text = value.ToString();
        }

        public int Y2
        {
            get => int.TryParse(txtBottomY.Text, out int y) ? y : 0;
            set => txtBottomY.Text = value.ToString();
        }
        #endregion

        public void Refresh()
        {
            LoadData();
        }

        public PageAvatars(WebView2 webView2 = null)
        {
            _webView2 = webView2;
            InitializeComponent();
        }

        private void PageAvatars_Load(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message);
            }
        }
        private List<Avatar> _avatars = null;

        private void LoadData()
        {
            ilbAvatars.Items.Clear();
            _avatars = DataHelper.GetAvatars().OrderBy(x => x.Name).ToList();

            foreach (Avatar avatar in _avatars)
            {
                try
                {
                    var imageBytes = Convert.FromBase64String(avatar.Image);
                    using (var ms = new MemoryStream(imageBytes))
                    {
                        Bitmap image = (Bitmap)Image.FromStream(ms);
                        ilbAvatars.AddImage(image, avatar.Name);
                    }
                }
                catch (Exception ex)
                {
                    this.ShowWarningTip($"加载头像 {avatar.Name} 失败: {ex.Message}");
                }
            }
        }

        private async void btnSnap_Click(object sender, EventArgs e)
        {
            try
            {
                if (_webView2 == null)
                {
                    this.ShowWarningTip("WebView2未初始化");
                    return;
                }

                // 获取截图区域
                var x = Math.Min(X1, X2);
                var y = Math.Min(Y1, Y2);
                var width = Math.Abs(X2 - X1);
                var height = Math.Abs(Y2 - Y1);

                if (width <= 0 || height <= 0)
                {
                    this.ShowWarningTip("请设置有效的截图区域");
                    return;
                }

                if (_webView2 == null)
                {
                    this.ShowWarningTip("WebView2控件未初始化");
                    return;
                }

                // 获取WebView2的截图
                pbAvatar.Image?.Dispose();
                pbAvatar.Image = await AuxHelper.CaptureWebViewAsync(_webView2, x, y, width, height);
            }
            catch (Exception ex)
            {
                this.ShowErrorTip($"截图失败: {ex.Message}");
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                // 清除文本框
                txtLeftX.Text = "0";
                txtTopY.Text = "0";
                txtRightX.Text = "0";
                txtBottomY.Text = "0";

                // 清除图片
                pbAvatar.Image = null;

                // 取消列表选中
                ilbAvatars.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
                this.ShowErrorTip($"清除失败: {ex.Message}");
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (pbAvatar.Image == null)
                {
                    this.ShowWarningTip("请先截取头像图片");
                    return;
                }

                var name = txtName.Text.Trim();
                if (string.IsNullOrEmpty(name))
                {
                    this.ShowWarningTip("请输入头像名称");
                    return;
                }

                // 将图片转换为Base64
                string base64Image;
                using (var ms = new MemoryStream())
                {
                    pbAvatar.Image.Save(ms, ImageFormat.Png);
                    base64Image = Convert.ToBase64String(ms.ToArray());
                }

                // 检查是否存在同名头像
                var existingAvatar = DataHelper.GetAvatarByName(name);
                if (existingAvatar == null && _avatars != null && _avatars.Any(x => x.Image == base64Image))
                {
                    existingAvatar = _avatars.First(x => x.Image == base64Image);
                    existingAvatar.Name = name;
                }                
                var avatar = existingAvatar ?? new Avatar { Name = name };
                avatar.Image = base64Image;

                bool hasImageMatches = existingAvatar?.ActionImageMatches?.Count > 0;
                var success = existingAvatar == null ?
                    DataHelper.InsertAvatar(avatar) :
                    DataHelper.UpdateAvatar(avatar);

                if (success)
                {
                    this.ShowSuccessTip(existingAvatar == null ? "保存成功" : "更新成功");
                    LoadData();
                    // 如果有关联的图像匹配操作，刷新图像匹配页面
                    if (hasImageMatches && _pageImageMatchActions != null)
                    {
                        _pageImageMatchActions.Refresh();
                    }
                }
                else
                {
                    this.ShowErrorTip("保存失败");
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorTip($"保存失败: {ex.Message}");
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (ilbAvatars.SelectedItem == null)
                {
                    this.ShowWarningTip("请先选择要删除的头像");
                    return;
                }

                var name = ilbAvatars.SelectedItem.Description;
                var avatar = DataHelper.GetAvatarByName(name);
                if (avatar == null)
                {
                    this.ShowWarningTip("未找到选中的头像数据");
                    return;
                }

                if (this.ShowAskDialog($"确定要删除头像 [{ilbAvatars.SelectedItem.Description}] 吗？"))
                {
                    if (DataHelper.DeleteAvatar(avatar.Id))
                    {
                        this.ShowSuccessTip("删除成功");
                        LoadData();
                    }
                    else
                    {
                        this.ShowErrorTip("删除失败");
                    }
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorTip($"删除失败: {ex.Message}");
            }
        }

        private void ilbAvatars_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (ilbAvatars.SelectedItem == null)
                {
                    txtName.Text = string.Empty;
                    pbAvatar.Image = null;
                    return;
                }

                string name = ilbAvatars.SelectedItem.Description;
                txtName.Text = name;
                pbAvatar.Image = ilbAvatars.SelectedItem.Image;
                if(DataHelper.GetAvatarByName(name).ActionImageMatches.Count > 0)
                    btnDelete.Visible = false;
                else
                    btnDelete.Visible = true;
            }
            catch (Exception ex)
            {
                this.ShowErrorTip($"加载头像失败: {ex.Message}");
            }
        }
    }
}
